package com.mmc.delay.config;

import com.mmc.delay.api.JobHandle;
import com.mmc.delay.api.Producer;
import com.mmc.delay.api.impl.DelayProducer;
import com.mmc.delay.bean.Job;
import com.mmc.delay.enums.TopicEnum;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;

import java.util.concurrent.atomic.AtomicInteger;

//@Configuration
public class DelayConfig {

    @Autowired
    private RedisTemplate redisTemplate;

    /**修改 redisTemplate 的key序列化方式  **/
    @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        GenericJackson2JsonRedisSerializer jackson2JsonRedisSerializer = new GenericJackson2JsonRedisSerializer();
        StringRedisTemplate stringRedisTemplate=new StringRedisTemplate(redisTemplate.getConnectionFactory());
        stringRedisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        stringRedisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        this.redisTemplate = stringRedisTemplate;
    }


    public static AtomicInteger orderCount=new AtomicInteger(0);
    public static AtomicInteger logCount=new AtomicInteger(0);
    public static AtomicInteger loginCount=new AtomicInteger(0);

    @Bean
    public Producer redisDelayService(){
        DelayProducer delayProducer = new DelayProducer(redisTemplate);
        delayProducer.setJobHandle(TopicEnum.ORDER.toString(), new JobHandle() {
            @Override
            public boolean handle(Job job) {
                System.out.println("收到订单消息："+job);
                orderCount.incrementAndGet();
                return true;
            }

            @Override
            public boolean errorHandle(Job job) {
                return false;
            }
        });
        delayProducer.setJobHandle(TopicEnum.LOG.toString(), new JobHandle() {
            @Override
            public boolean handle(Job job) {
                System.out.println("收到日志消息："+job);
                logCount.incrementAndGet();
                return true;
            }

            @Override
            public boolean errorHandle(Job job) {
                return false;
            }
        });
        delayProducer.setJobHandle(TopicEnum.LOGIN.toString(), new JobHandle() {
            @Override
            public boolean handle(Job job) {
                System.out.println("收到登录消息："+job);
                loginCount.incrementAndGet();
                return true;
            }

            @Override
            public boolean errorHandle(Job job) {
                return false;
            }
        });
        return delayProducer;
    }



}
